package com.wht.ai.anythingLLM;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.noear.solon.ai.chat.*;
import org.noear.solon.ai.chat.dialect.AbstractDialect;
import org.noear.solon.ai.chat.message.AssistantMessage;
import org.noear.solon.ai.chat.message.ChatMessage;

import java.util.Date;
import java.util.List;

/**
 * @author by HaiTao.Wang on 2025/2/18.
 */
public class AnythingLLMDialect extends AbstractDialect {

    @Override
    public boolean matched(ChatConfig config) {
        return "anythingLLM".equals(config.provider());
    }

    @Override
    public String buildRequestJson(ChatConfig config, ChatOptions options, List<ChatMessage> messages, boolean stream) {

        return JSONUtil.createObj().set("message", messages.get(0).getContent()).set("mode", "chat").toString();
    }

    @Override
    public boolean parseResponseJson(ChatConfig config, ChatResponseAmend resp, String json) {

        json = json.replaceFirst("data:", "");

        JSONObject parseObj = JSONUtil.parseObj(json);

        resp.setFinished(parseObj.getBool("close"));
        resp.addChoice(new ChatChoice(0, new Date(), parseObj.getStr("close"),
                new AssistantMessage(parseObj.getStr("textResponse"), null, null, null)));

        return true;
    }
}
